package com.youth.framework.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.youth.framework.core.InvokeResult;

public class FrameExceptionHandlerResolver implements HandlerExceptionResolver{
	
	private final String error_default_view = "/errors/default"; 
	private final String error_404_view = ""; 
	private final String error_500_view = ""; 

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		System.out.println("============");
		String servletPath = request.getServletPath();
		if (null != servletPath && servletPath.endsWith(".json")){
			String json = null;
			try {
				response.setCharacterEncoding("utf-8");
				response.getWriter().write(handlerException(ex));
				response.getWriter().flush();
			} catch (IOException e) {
				//json = handlerException
				e.printStackTrace();
			}
			
			return new ModelAndView();
		}
//		try {
			//response.sendError(HttpServletResponse.SC_BAD_REQUEST);
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return new ModelAndView("error_default_view");
	}
	
	private String handlerException(Exception ex){
		InvokeResult<Object> ir = new InvokeResult<Object>() ;
		String mess = ex.getMessage();
		if(mess==null){
			mess = "Error : " + mess;
		}
		ir.setSuccessful(false);
		ir.setMessage(mess);
		return JSON.toJSONString(ir);
		
	}

}
